package com.egg.mall.service.brand.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.egg.common.core.exception.CustomException;
import com.egg.common.mybatis.service.impl.BaseServiceImpl;
import com.egg.common.util.JsonUtil;
import com.egg.mall.entity.brand.Brand;
import com.egg.mall.mapper.brand.BrandMapper;
import com.egg.mall.model.request.BrandPostOrPut;
import com.egg.mall.service.brand.IBrandService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.Serializable;
import java.util.Optional;


/**
 * @author east
 * @since 2022-07-25
 */
@Slf4j
@Service
public class BrandServiceImpl extends BaseServiceImpl<BrandMapper, Brand> implements IBrandService {


    /**
     * 名称是否重复
     *
     * @param name 名称
     * @return boolean true 存在 / false 不存在
     */
    public boolean existName(String name) {
        return existName(name, Optional.empty());
    }

    /**
     * 名称是否重复
     *
     * @param name     名称
     * @param filterId 排除id
     * @return boolean true 存在 / false 不存在
     */
    public boolean existName(String name, Optional<? extends Serializable> filterId) {
        if (ObjectUtil.isEmpty(name)) {
            return false;
        }
        LambdaQueryWrapper<Brand> qw = buildLambdaSortQw();
        qw.eq(Brand::getName, name);
        filterId.ifPresent(o -> qw.notIn(Brand::getId, o));
        return count(qw) > 0;
    }

    @Transactional(rollbackFor = Throwable.class)
    @Override
    public Long add(BrandPostOrPut add) {
        if (existName(add.getName())) {
            throw new CustomException("名称重复");
        }
        Brand brand = JsonUtil.objToObj(add, Brand.class);
        baseSave(brand);
        return brand.getId();
    }

    @Transactional(rollbackFor = Throwable.class)
    @Override
    public Long edit(String id, BrandPostOrPut param) {
        Brand exist = baseGetById(id);
        Brand info = JsonUtil.objToObj(param, Brand.class);
        if (existName(info.getName(), Optional.of(exist.getId()))) {
            throw new CustomException("名称重复");
        }
        info.setId(exist.getId());
        baseSave(info);
        return info.getId();
    }


}
